<script setup lang="ts">
import { common } from '@/utils/common'
import { inject, reactive } from 'vue'
import { taskStore } from '@/store/task'
import { myStore } from '@/store/my'
import { uploadImageAPI, userModifyAPI } from '@/api/my'
import { Toast } from 'vant';

    const store = myStore()
    const { closeChange } = inject('popup')
    const Form = reactive({
        name: '',
        sex: '',
        birthday: '',
        WorkTime: '',
        city: '',
        area: '',
        fileList: []
    })
    const state = reactive({
        minDate: new Date(1980,1,1), // 最小日期
        maxDate: new Date(), // 最大日期（当前日期）
        showSex: false,
        showBirthday: false,
        showWorkTime: false,
        showCity: false,
        loading: false
    })
    // 回填个人信息
    const setInfo = () => {
        Form.name = store.state.userInfo.user_name
        Form.sex = common.sex(store.state.userInfo.sex)
        Form.birthday = store.state.userInfo.birthday
        Form.WorkTime = store.state.userInfo.work_time
        Form.city = store.state.userInfo.city
        Form.area = store.state.userInfo.area
        if(store.state.userInfo.it_head){
            Form.fileList = [{
                url: store.state.userInfo.it_head
            }]
        }
    }    
    // 如果store里没有个人信息 调用接口
    if(!store.state.userInfo.id) {
        // 匿名函数
        (async function(){
            await store.getUserInfo()
            setInfo()
        })()
    }else{
        setInfo()
    }
    
    const tsStore = taskStore()

    // 获取地区列表
    if (!tsStore.areaList.value) tsStore.getCityList()

    // 性别列表
    const sexList = [
        {name: '男'},
        {name: '女'}
    ]
    // 上传文件
    const afterRead = async (file) => {
        file.status = 'uploading'
        file.message = '上传中...'
        let data = new FormData()
        data.append('user', 'test')
        data.append('file', file.file)
        const res = await uploadImageAPI(data)
        file.url = res.imageUrl
        file.status = 'done'
        file.message = '上传成功'        
        Form.fileList = [file]
    }
    // 性别选择
    const sexSelect = (val) => {
        Form.sex = val.name
    }
    // 选择出生年月
    const birthdayConfirm = (val) => {
        Form.birthday = val.getFullYear() + '-' + (val.getMonth()+1)
        state.showBirthday = false
    }
    // 选择工作时间
    const WorkTimeConfirm = (val) => {
        Form.WorkTime = val.getFullYear() + '-' + (val.getMonth()+1)
        state.showWorkTime = false
    }
    // 城市确认
    const cityConfirm = (val) => {
        Form.city = val[0].text
        Form.area = val[1].text
        state.showCity = false
    }
    // 文件删除前的回调函数
    const deleteFile = () => {
        // 清空文件列表
        Form.fileList = []
    }
    // 提交
    const setUserModify = async () => {
        if(Form.fileList.length===0){
            Toast('请上传头像')
            return
        }
        if(!Form.name){
            Toast('请填写姓名')
            return
        }
        if(!Form.sex){
            Toast('请选择性别')
            return
        }
        if(!Form.birthday){
            Toast('请选择出生年月')
            return
        }
        if(!Form.WorkTime){
            Toast('请选择参加工作时间')
            return
        }
        if(!Form.city){
            Toast('请选择城市')
            return
        }
        state.loading = true
        const res = await userModifyAPI({
            "user_name": Form.name, 
            "sex": Form.sex==='男'?1:Form.sex==='女'?2:'', 
            "birthday": Form.birthday, 
            "work_time": Form.WorkTime, 
            "city": Form.city, 
            "area": Form.area, 
            "it_head": Form.fileList[0].url,
            "type": 1 
        })
        if(res){
            store.getUserInfo()
        }
        Toast(res.msg)
        state.loading = false
    }
</script>


<template>
    <van-nav-bar
        title="个人信息"
        left-arrow
        @click-left="closeChange"
    />
   <div class="user-page">
        <van-form @submit="setUserModify">
            <div class="user-pic">
                <van-uploader 
                    v-model="Form.fileList"
                    :after-read="afterRead"
                    :before-delete ="deleteFile"
                    :max-count="1"
                    accept=".jpg,.png"
                />
            </div>
            <div class="user-item">
                <h5>姓名</h5>
                <van-field
                    v-model="Form.name"
                    placeholder="请输入您的姓名"
                />
            </div>
            <div class="user-item">
                <h5>性别</h5>
                <van-field
                    v-model="Form.sex"
                    placeholder="请选择您的性别"
                    is-link
                    readonly
                    @click="state.showSex=true"
                />
                <van-action-sheet
                    v-model:show="state.showSex"
                    :actions="sexList"
                    cancel-text="取消"
                    close-on-click-action
                    @select="sexSelect"
                />
            </div>
            <div class="user-item">
                <h5>出生日期</h5>
                <van-field
                    v-model="Form.birthday"
                    placeholder="请选择您的出生日期"
                    is-link
                    @click="state.showBirthday=true"
                />
                <van-action-sheet v-model:show="state.showBirthday">
                    <van-datetime-picker
                        type="year-month"
                        title="选择年月"
                        :min-date="state.minDate"
                        :max-date="state.maxDate"
                        @confirm="birthdayConfirm"
                        @cancel="state.showBirthday=false"
                    />
                </van-action-sheet>
            </div>
            <div class="user-item">
                <h5>参加工作时间</h5>
                <van-field
                    v-model="Form.WorkTime"
                    placeholder="请选择您参加工作的时间"
                    is-link
                    @click="state.showWorkTime=true"
                />
                <van-action-sheet v-model:show="state.showWorkTime">
                    <van-datetime-picker
                        type="year-month"
                        title="选择年月"
                        :min-date="state.minDate"
                        :max-date="state.maxDate"
                        @confirm="WorkTimeConfirm"
                        @cancel="state.showWorkTime=false"
                    />
                </van-action-sheet>
            </div>
            <div class="user-item">
                <h5>所在城市</h5>
                <van-field
                    v-model="Form.city"
                    placeholder="请选择您的城市"
                    @click="state.showCity=true"
                    is-link
                />
                <van-action-sheet v-model:show="state.showCity">
                    <van-picker
                        :columns="tsStore.areaList"
                        @confirm="cityConfirm"
                        @cancel="state.showCity=false"
                    />
                </van-action-sheet>
            </div>
            <button class="wy-confirm-btn" native-type="submit">完成</button>
        </van-form>
   </div>

</template>
<style scoped>
>>>.van-image__img{
    border-radius: 50%;
}
>>>.van-uploader__upload{
    margin: 0;
}
.user-page{
    margin: 0 0.6rem;
}
.user-pic{
    text-align: center;
    padding: 0.67rem;
    margin-bottom: 1.47rem;
    border-bottom: 1px solid #f3f3f3;
}
.user-pic img{
    width: 3.7rem;
    height: 3.7rem;
    border-radius: 50%;
}

.wy-confirm-btn{
    height: 2.35rem;
    line-height: 2.35rem;
    background: linear-gradient(90deg, #FEA829, #FE8F27);
    border-radius: 0.27rem;
    width: calc(100vw - 1.2rem);
    border: 0;
    position: fixed;
    left: 0;
    bottom: 0;
    margin: 0 0.6rem 0.6rem;
    font-size: 0.8rem;
    color: #FFFFFF;
}
</style>
